<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

class JFX_Module_Jfxcss extends JFX_Module {

    public $keyname = 'jfxcss';
    public $title = 'JFX CSS';
    public $version = '0.2.3';
    public $dependencies = array(

    );
    public $browserVersions = array('lt IE 6', 'IE 6', 'lt IE 7', 'IE 7', 'lt IE 8', 'IE 8');

    public function __construct(){
        parent::__construct();

    }

    public function editPageCss($PAGE){
        $_GET['page'] = $PAGE->get('id');

        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $LANG = JFX::registry('lang');
        $THEME = JFX::registry('JFX_Theme');

        include($this->dirname.'/admin-actions/manage-stylesheet-associations.php');
    }

    public function getPageButtons($pageid){
        $buttons = array();
        $button = array(
            'id' => 'JFXCSSButton',
            'image' => 'lightening.png',
            'title' => $this->lang('manage_stylesheet_associations'),
            'alt' => $this->lang('css'),
            'click' => '
                var href = "'.$this->adminUrl.'/manage-stylesheet-associations/?page='.$pageid.'&KeepThis=true&TB_iframe=true&height=500&width=700";
                tb_show("'.$this->lang('manage_stylesheet_associations').'", href, false);
                $(\'#TB_window\').unload(function(){
                    window.location = window.location;
                });'
        );
        //$buttons[] = $button;

        $button = new JFX_Page_Button;
        $button->id = 'JFXCSSButton';
        $button->imageUrl = $this->imageUrl.'/lightening.png';
        $button->alternativeText = $this->lang('css');
        $button->title = $this->lang('css');
        $button->moduleName = $this->keyname;
        $button->moduleMethod = 'editPageCss';
        $button->pageId = $pageid;

        $buttons[] = $button;

        return $buttons;
    }


    public function showCssLinksForPage($pageid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $VIEW = JFX::registry('JFX_View');

        $css = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}jfxcss_pages_to_stylesheets WHERE page_id = '{$pageid}' ORDER BY sorting ASC");

        foreach($css as $k=>$v){
            $cssData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}jfxcss_stylesheets WHERE keyname = '{$v['css_key']}'");
            

            switch($cssData['browser_version']){
                case 'lt IE 6':
                case 'IE 6':
                case 'lt IE 7':
                case 'IE 7':
                case 'lt IE 8':
                case 'IE 8':
                    $VIEW->addIeCssLink($CONFIG->baseUrl.$CONFIG->moduleCssFolder.'/'.$this->keyname.'/'.$v['css_key'].'.css', $cssData['browser_version']);
                break;
                default:
                    $this->addStylesheet($v['css_key'].'.css');
            }

        }
    }

    public function printCssFile($filename){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $fileParts = explode('.', $filename);
        
        $cssKey = preg_replace('/[^a-zA-Z0-9]/', '', $fileParts[0]);
        if($DB->countRows($CONFIG->dbprefix.'jfxcss_stylesheets', "keyname = '{$cssKey}'")>0){
            while(ob_get_level()>0) ob_end_clean();

            $searches = array(
                ':|imgUrl|:',
                ':|imageUrl|:',
                ':|cssUrl|:',
                ':|jsUrl|:',
                ':|moduleUrl|:'
            );
            $replacements = array(
                $CONFIG->baseUrl.$CONFIG->moduleImageFolder,
                $CONFIG->baseUrl.$CONFIG->moduleImageFolder,
                $CONFIG->baseUrl.$CONFIG->moduleCssFolder,
                $CONFIG->baseUrl.$CONFIG->moduleJsFolder,
                $CONFIG->baseUrl.$CONFIG->moduleServerFolder
            );

            //header('Content-type: text/css');
            if($fileParts[1]=='htc'){
                header('Content-type: text/x-component');
            }else{
                header('Content-type: text/css');
            }
            $cssid = $DB->oneValue($CONFIG->dbprefix.'jfxcss_stylesheets', 'id', "keyname = '{$cssKey}'");
            $cssString = @file_get_contents($this->dirname.'/files/'.$cssid.'.css');
            $cssString = str_replace($searches, $replacements, $cssString);
            echo $cssString;
            exit;
        }else{
            return parent::printCssFile($filename);
        }
    }

    public function getBlockActions(){
        return array(
            
        );
    }

    public function updateSettings($params){

        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');

        $mData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}jfxmenu_blocks_to_menus WHERE block_id = '{$params['id']}'");
        if(!is_array($mData)) $defaultMenu = $DB->oneValue($CONFIG->dbprefix.'jfxmenu_menus', 'keyname', '1');
        else $defaultMenu = $mData['keyname'];

        if(Antz_IntelliForm::submitted('select-menu')){
            $error = false;
            $menu = preg_replace('/[^a-zA-Z0-9]/', '', post('menu'));
            if($DB->countRows($CONFIG->dbprefix.'jfxmenu_menus', "keyname = '{$menu}'")==0){
                $error = true;
                JFX::addError($this->lang('invalid_menu'));
            }
            if(!$error){
                $dbParams = array(
                    'block_id' => $params['id'],
                    'menu_key' => $menu
                );
                if($DB->countRows($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', "block_id = '{$params['id']}' AND menu_key = '{$menu}'")==0){
                    // insert
                    $DB->insert($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', $dbParams);
                }else{
                    // update
                    $DB->update($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', $dbParams, "block_id = '{$params['id']}' AND menu_key = '{$menu}'");
                }
                JFX::addSuccess($this->lang('success'));
            }
        }


        $menuOpts = array();
        $menus = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}jfxmenu_menus ORDER BY keyname ASC");
        foreach($menus as $k=>$v){
            $menuOpts[$v['keyname']] = $this->getContentLang('title', $v['keyname']);
        }
        $formFields = array(
            array(
                'type' => 'select',
                'name' => 'menu',
                'value' => post('menu', $defaultMenu),
                'options' => $menuOpts,
                'label' => $this->lang('menu')
            ),
            array(
                'type' => 'submit',
                'name' => 'submitBtn',
                'value' => $this->lang('submit'),
                'label' => '&nbsp;'
            )
        );
        echo JFX::makeRapidForm($formFields, $this->lang('select_menu'), 'select-menu');
    }


    public function getContent($params){
        return '';
    }

    public function prepare($details){
        return $this->getContent($details);
    }
    


    public function admin($url, $dirname){
        //$this->resetLanguages();
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $SMARTY->assign('actionUrl', $url);
        $LANG = JFX::registry('lang');
        $THEME = JFX::registry('JFX_Theme');
        
        $THEME->addBreadcrumb($this->adminUrl, $this->getTitle());
        $THEME->breadcrumbs[0]->set('icon', $this->imageUrl.'/lightening.png');

        $this->addStylesheet('admin.css');

        $tabs = array(
            array(
                'keyname' => 'list',
                'title' => $this->lang('list'),
                'url' => $url.'/list',
                'class_name' => ''
            ),
            array(
                'keyname' => 'new-stylesheet',
                'title' => $this->lang('new'),
                'url' => $url.'/new-stylesheet/?KeepThis=true&amp;TB_iframe=true&amp;height=500&amp;width=700',
                'class_name' => ''
            ),
            array(
                'keyname' => 'sort-default-stylesheets',
                'title' => $this->lang('sort_default'),
                'url' => $url.'/sort-default-stylesheets/?KeepThis=true&amp;TB_iframe=true&amp;height=500&amp;width=700',
                'class_name' => ''
            )
        );

        // find our selected tab
        $urlParts = explode('?', $_SERVER['REQUEST_URI']);
        $urlParts = explode('/', $urlParts[0]);
        foreach($urlParts as $k=>$v){
            if($v == $this->keyname) break;
        }
        $selectedTab = (array_key_exists($k+1, $urlParts))
            ? $urlParts[$k+1]
            : ''
            ;

        if($selectedTab == ''){
            $selectedTab = 'list';
        }

        foreach($tabs as $k=>$tab){
            if($selectedTab == $tab['keyname']){
                $tabs[$k]['class_name'] .= ' jfxcss-selected';
            }
        }

        //include('admin-actions/tabs.php');

        $selectedTab = str_replace('../', '/', $selectedTab);

        
            if(file_exists($this->dirname.'/admin-actions/'.$selectedTab.'.php')) include($this->dirname.'/admin-actions/'.$selectedTab.'.php');
            else echo $selectedTab.'.php does not exists';
        

    }


    public function install(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/install.php');
    }


    public function uninstall(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/uninstall.php');
    }




}